<template>
  <div>
    <img :src="img" class="imgSize" />
    <div>
      <el-button @click="getPoster">生成海报</el-button>
      <el-button @click="download">下载</el-button>
    </div>
    <canvas ref="canvas" width="500" height="400" class="pannel"></canvas>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      img: "https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3671469745,3459667453&fm=26&gp=0.jpg",
    }
  },
  computed: {
    canvas() {
      return this.$refs.canvas
    },
    context() {
      return this.canvas.getContext("2d")
    },
  },
  methods: {
    getPoster() {
      //  将需要生成海报的图片画进去canvas
      let img = new Image()
      img.src = this.img
      img.onload = () => {
        // 保持原图比例
        const percent = this.canvas.width / this.canvas.height
        this.context.drawImage(img, 0, 0, this.canvas.offsetWidth, this.canvas.offsetWidth / percent)
        // 画字体
        this.context.font = "30px 黑体"
        this.context.fillStyle = "#ccc"
        this.context.fillText("你是大哥不许难过", 220, 320)
      }
    },
    download() {
      // 本地照片能下载，但是跨域的图片不能下载
      let a = document.createElement('a')
      a.href = this.canvas.toDataURL("image/png")
      a.download = "明天.png"
      a.click()
    },
  },
}
</script>
<style lang="less" scoped>
.pannel {
  border: 1px solid #000000;
  background: #fff;
  margin-top: 20px;
}
.imgSize {
  width: 300px;
}
</style>
